package com.example.weather_forecast;

import android.app.TimePickerDialog;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.util.Calendar;

public class NotificationSettingsActivity extends AppCompatActivity {

    // UI元素
    private Switch switchEnableNotification;
    private Switch switchDailyForecast;
    private TextView textNotificationTime;
    private Switch switchEnableAlert;
    private CheckBox checkboxRain;
    private CheckBox checkboxTyphoon;
    private CheckBox checkboxHeat;
    private CheckBox checkboxCold;
    private Switch switchSound;
    private Switch switchVibration;
    private Button buttonSave;

    // 设置存储
    private SharedPreferences preferences;
    private static final String PREFS_NAME = "WeatherNotificationSettings";

    // 设置项的键名
    private static final String KEY_ENABLE_NOTIFICATION = "enable_notification";
    private static final String KEY_DAILY_FORECAST = "daily_forecast";
    private static final String KEY_NOTIFICATION_TIME_HOUR = "notification_time_hour";
    private static final String KEY_NOTIFICATION_TIME_MINUTE = "notification_time_minute";
    private static final String KEY_ENABLE_ALERT = "enable_alert";
    private static final String KEY_ALERT_RAIN = "alert_rain";
    private static final String KEY_ALERT_TYPHOON = "alert_typhoon";
    private static final String KEY_ALERT_HEAT = "alert_heat";
    private static final String KEY_ALERT_COLD = "alert_cold";
    private static final String KEY_SOUND = "sound";
    private static final String KEY_VIBRATION = "vibration";

    // 通知时间
    private int notificationHour = 7;
    private int notificationMinute = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notification_settings);

        // 初始化SharedPreferences
        preferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);

        // 初始化UI元素
        initUIElements();

        // 加载保存的设置
        loadSettings();

        // 设置监听器
        setupListeners();
    }

    private void initUIElements() {
        switchEnableNotification = findViewById(R.id.switch_enable_notification);
        switchDailyForecast = findViewById(R.id.switch_daily_forecast);
        textNotificationTime = findViewById(R.id.text_notification_time);
        switchEnableAlert = findViewById(R.id.switch_enable_alert);
        checkboxRain = findViewById(R.id.checkbox_rain);
        checkboxTyphoon = findViewById(R.id.checkbox_typhoon);
        checkboxHeat = findViewById(R.id.checkbox_heat);
        checkboxCold = findViewById(R.id.checkbox_cold);
        switchSound = findViewById(R.id.switch_sound);
        switchVibration = findViewById(R.id.switch_vibration);
        buttonSave = findViewById(R.id.button_save);
    }

    private void loadSettings() {
        // 加载通知设置
        switchEnableNotification.setChecked(preferences.getBoolean(KEY_ENABLE_NOTIFICATION, true));
        switchDailyForecast.setChecked(preferences.getBoolean(KEY_DAILY_FORECAST, true));

        // 加载通知时间
        notificationHour = preferences.getInt(KEY_NOTIFICATION_TIME_HOUR, 7);
        notificationMinute = preferences.getInt(KEY_NOTIFICATION_TIME_MINUTE, 0);
        updateTimeDisplay();

        // 加载预警设置
        switchEnableAlert.setChecked(preferences.getBoolean(KEY_ENABLE_ALERT, true));
        checkboxRain.setChecked(preferences.getBoolean(KEY_ALERT_RAIN, true));
        checkboxTyphoon.setChecked(preferences.getBoolean(KEY_ALERT_TYPHOON, true));
        checkboxHeat.setChecked(preferences.getBoolean(KEY_ALERT_HEAT, true));
        checkboxCold.setChecked(preferences.getBoolean(KEY_ALERT_COLD, true));

        // 加载提醒方式设置
        switchSound.setChecked(preferences.getBoolean(KEY_SOUND, true));
        switchVibration.setChecked(preferences.getBoolean(KEY_VIBRATION, true));
    }

    private void setupListeners() {
        // 通知时间选择器
        textNotificationTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showTimePickerDialog();
            }
        });

        // 总通知开关状态变化监听
        switchEnableNotification.setOnCheckedChangeListener((buttonView, isChecked) -> {
            // 更新UI状态
            updateNotificationDependentControls(isChecked);
        });

        // 预警开关状态变化监听
        switchEnableAlert.setOnCheckedChangeListener((buttonView, isChecked) -> {
            // 更新UI状态
            updateAlertDependentControls(isChecked);
        });

        // 保存按钮点击事件
        buttonSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveSettings();
                Toast.makeText(NotificationSettingsActivity.this, "设置已保存", Toast.LENGTH_SHORT).show();

                // 如果通知已启用，设置系统通知
                if (switchEnableNotification.isChecked()) {
                    scheduleNotifications();
                } else {
                    cancelNotifications();
                }
            }
        });

        // 初始状态更新
        updateNotificationDependentControls(switchEnableNotification.isChecked());
        updateAlertDependentControls(switchEnableAlert.isChecked());
    }

    private void updateNotificationDependentControls(boolean enabled) {
        switchDailyForecast.setEnabled(enabled);
        textNotificationTime.setEnabled(enabled);
        switchEnableAlert.setEnabled(enabled);

        // 如果总通知被禁用，连带禁用预警相关控件
        boolean alertControlsEnabled = enabled && switchEnableAlert.isChecked();
        updateAlertDependentControls(alertControlsEnabled);
    }

    private void updateAlertDependentControls(boolean enabled) {
        checkboxRain.setEnabled(enabled);
        checkboxTyphoon.setEnabled(enabled);
        checkboxHeat.setEnabled(enabled);
        checkboxCold.setEnabled(enabled);
    }

    private void showTimePickerDialog() {
        TimePickerDialog timePickerDialog = new TimePickerDialog(
                this,
                (view, hourOfDay, minute) -> {
                    notificationHour = hourOfDay;
                    notificationMinute = minute;
                    updateTimeDisplay();
                },
                notificationHour,
                notificationMinute,
                true);
        timePickerDialog.show();
    }

    private void updateTimeDisplay() {
        // 更新时间显示，格式为HH:MM
        String time = String.format("%02d:%02d", notificationHour, notificationMinute);
        textNotificationTime.setText(time);
    }

    private void saveSettings() {
        SharedPreferences.Editor editor = preferences.edit();

        // 保存通知设置
        editor.putBoolean(KEY_ENABLE_NOTIFICATION, switchEnableNotification.isChecked());
        editor.putBoolean(KEY_DAILY_FORECAST, switchDailyForecast.isChecked());
        editor.putInt(KEY_NOTIFICATION_TIME_HOUR, notificationHour);
        editor.putInt(KEY_NOTIFICATION_TIME_MINUTE, notificationMinute);

        // 保存预警设置
        editor.putBoolean(KEY_ENABLE_ALERT, switchEnableAlert.isChecked());
        editor.putBoolean(KEY_ALERT_RAIN, checkboxRain.isChecked());
        editor.putBoolean(KEY_ALERT_TYPHOON, checkboxTyphoon.isChecked());
        editor.putBoolean(KEY_ALERT_HEAT, checkboxHeat.isChecked());
        editor.putBoolean(KEY_ALERT_COLD, checkboxCold.isChecked());

        // 保存提醒方式设置
        editor.putBoolean(KEY_SOUND, switchSound.isChecked());
        editor.putBoolean(KEY_VIBRATION, switchVibration.isChecked());

        editor.apply();
    }

    // 调度通知
    private void scheduleNotifications() {
        // 创建/更新每日天气预报通知
        if (switchDailyForecast.isChecked()) {
            NotificationScheduler.scheduleDailyForecast(
                    this,
                    notificationHour,
                    notificationMinute,
                    switchSound.isChecked(),
                    switchVibration.isChecked()
            );
        }

        // 设置天气预警监听（如果启用）
        if (switchEnableAlert.isChecked()) {
            WeatherAlertManager.setWeatherAlertSettings(
                    this,
                    checkboxRain.isChecked(),
                    checkboxTyphoon.isChecked(),
                    checkboxHeat.isChecked(),
                    checkboxCold.isChecked(),
                    switchSound.isChecked(),
                    switchVibration.isChecked()
            );
        }
    }

    // 取消所有通知
    private void cancelNotifications() {
        NotificationScheduler.cancelAllScheduledNotifications(this);
        WeatherAlertManager.disableAllAlerts(this);
    }
}